using System;
using Impact.Infrastructure.Membership;
using Impact.Views;
using StructureMap;

namespace Impact.Controllers
{
    /// <summary>
    /// Controller responsible for the installation process
    /// </summary>
    public class InstallController 
    {
        private IInstallerView view;

        /// <summary>
        /// default constructor
        /// </summary>
        /// <param name="view">the view this controller will use for front-end control</param>
        public InstallController(IInstallerView view)
        {
            this.view = view;
        }

        /// <summary>
        /// initializes the view
        /// </summary>
        /// <param name="isFirstLoad">true if this is the first time the view has been loaded (not a postback)</param>
        public void Initialize(bool isFirstLoad)
        {
            if(isFirstLoad)
            {
                view.CurrentStep = 1;
                view.ShowStep(1);
            }
        }

        /// <summary>
        /// loads the next step in the install process
        /// </summary>
        public void NextStep()
        {
            int nextStep = -1;
            if (view.IsValid)
            {
                switch (view.CurrentStep)
                {
                    case 1:
                        nextStep = 2;
                        break;
                    case 2:
                        CreateUser();
                        nextStep = 3;
                        break;
                    case 3:
                        nextStep = 99;
                        break;
                    case 99:
                        view.Redirect("~/");
                        return;
                    default:
                        throw new ArgumentException(string.Format("No next step for step {0}", view.CurrentStep));
                }
                view.ShowStep(nextStep);
                view.CurrentStep = nextStep;
            }
        }

        private void CreateUser()
        {
            IMembershipService membershipService = ObjectFactory.GetInstance<IMembershipService>();
            membershipService.CreateUser(view.Administrator.Username,
                                         view.Administrator.Password, view.Administrator.Email);
        }
    }
}
